package exts

import (
	"context"
	"gitee.com/tietang/terrace-go/v2/base/plugin"
	"gitee.com/tietang/terrace-go/v2/base/starter/ivalidator"
	"gitee.com/tietang/terrace-go/v2/example/order"
)

var ext order.CreateOrderServiceExt = new(OrderCreatedValidatorExt)
var _ plugin.PluginId = new(OrderCreatedValidatorExt)

func init() {
	plugin.Register(ext)
}

type OrderCreatedValidatorExt struct {
	order.CreateOrderServiceExt
}

func (o *OrderCreatedValidatorExt) Ability() string {
	return "default"
}

func (o *OrderCreatedValidatorExt) Check(ctx context.Context, in interface{}) bool {
	dto := in.(*order.OrderDTO)
	return dto.Source == 1
}

func (o *OrderCreatedValidatorExt) PluginCode() string {
	return order.CreateOrderServicePluginId
}

func (o *OrderCreatedValidatorExt) OnValidate(ctx context.Context, in *order.OrderDTO) error {
	//验证输入参数
	if in.Source != 1 {
		return nil
	}
	if err := ivalidator.Validate().Var(in.PayAmount, "required"); err != nil {
		return err
	}
	return nil
}

func (o *OrderCreatedValidatorExt) Pre(ctx context.Context, in *order.OrderDTO) error {
	in.Status = 1
	return nil
}

func (o *OrderCreatedValidatorExt) Post(ctx context.Context, in *order.OrderDTO, out *order.OrderDTO) error {
	return nil
}
